<?php


namespace App\Http\Controllers\Admin\Content;


use App\Http\Controllers\AdminController;
use App\Models\Content\Adv;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AdvController extends AdminController
{

    public function data(Request $request)
    {
        $model = Adv::query()->select(['id', 'sort', 'name', 'thumb', 'status', 'created_at', 'updated_at']);
        if ($keywords = $request->get('keywords')) {
            $model->where('name', 'like', filterStr($keywords).'%');
        }
        $list = $model->orderBy('sort')->paginate($request->get('limit', 10));
        return $this->succeed([
            'total' => $list->total(),
            'rows'  => $list->items(),
        ]);
    }

    public function store(Request $request)
    {
        $request->validate(['name' => 'required|max:50']);
        $data = $request->only(['name', 'thumb', 'url', 'sort', 'status']);
        try {
            DB::transaction(function () use ($data) {
                $model = Adv::query()->create([
                    'name' => $data['name'],
                    'thumb' => $data['thumb'],
                    'url' => $data['url'],
                    'sort' => (int)$data['sort'],
                    'status' => (int)$data['status'],
                ]);
                $this->createSyslog('添加广告位', $model);
            });
            return $this->succeed();
        }catch (\Exception $e) {
            report($e);
        }
        return $this->error();
    }

    public function update(Request $request, $id)
    {
        $request->validate(['name' => 'required|max:50']);
        $item = Adv::query()->findOrFail($id);
        $data = $request->only(['name', 'thumb', 'url', 'sort', 'status']);
        try {
            DB::transaction(function () use ($item, $data) {
                $item->update([
                    'name' => $data['name'],
                    'thumb' => $data['thumb'],
                    'url' => $data['url'],
                    'sort' => (int)$data['sort'],
                    'status' => (int)$data['status'],
                ]);
                $this->createSyslog('更新广告位', $item);
            });
            return $this->succeed();
        }catch (\Exception $e) {
            report($e);
        }
        return $this->error();
    }

    public function destroy(Request $request)
    {
        $request->validate(['ids' => 'required|array|size:'.static::QUERY_LIMIT]);
        $ids = $request->get('ids');
        try {
            DB::transaction(function () use ($ids) {
                Adv::query()->whereIn('id', $ids)->limit(static::QUERY_LIMIT)->delete();
                $this->createSyslog('删除广告位', $ids);
            });
            return $this->succeed();
        }catch (\Exception $e) {
            report($e);
        }
        return $this->error();
    }
}
